package com.example.testproj.c0301;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * @des:
 * @author: 芮勤
 * @date: 2019/5/21 20:54
 * @see {@link }
 */
public class MyViewGroup extends ViewGroup {
    private static final String TAG = "MyViewGroup";
    public MyViewGroup(Context context) {
        super(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count=getChildCount();
        Log.d(TAG, "onLayout: t==="+t);
        int curHeight=t;
        for (int i=0;i<count;i++){
            View childView=getChildAt(i);
            int height=childView.getMeasuredHeight();
            int width=childView.getMeasuredWidth();
            childView.layout(l,curHeight,l+width,curHeight+height);
            curHeight+=height;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //触发子View的onMeasure
        measureChildren(widthMeasureSpec,heightMeasureSpec);

        int widthMode=MeasureSpec.getMode(widthMeasureSpec);
        int widthSize=MeasureSpec.getSize(widthMeasureSpec);
        int heightMode=MeasureSpec.getMode(heightMeasureSpec);
        int heightSize=MeasureSpec.getSize(heightMeasureSpec);

        int childCount=getChildCount();
        if (childCount==0){
            setMeasuredDimension(0,0);
        }else {
            if (widthMode==MeasureSpec.AT_MOST&&heightMode==MeasureSpec.AT_MOST){
                int height=getTotleHeight();
                int width=getMaxChildWidth();
                setMeasuredDimension(width,height);
            }else if (widthMode==MeasureSpec.AT_MOST){
                int width=getMaxChildWidth();
                setMeasuredDimension(width,heightSize);
            }else if (heightMode==MeasureSpec.AT_MOST){
                int height=getTotleHeight();
                setMeasuredDimension(widthSize,height);
            }
        }
    }

    private int getMaxChildWidth() {
        int childCount=getChildCount();
        int maxWidth=0;
        for (int i=0;i<childCount;i++){
            View childView=getChildAt(i);
            if (maxWidth<childView.getMeasuredWidth()){
                maxWidth=childView.getMeasuredWidth();
            }
        }
        return maxWidth;
    }

    private int getTotleHeight() {
        int childCount=getChildCount();
        int height=0;
        for (int i=0;i<childCount;i++){
            View childView=getChildAt(i);
            height+=childView.getMeasuredHeight();
        }
        return height;
    }
}
